<?php
class Login_Ldap {
    private static $instance;
    private $user;
    private $pwd;
    private $ldaphost; // '10.11.6.151';
    private $ldapport;//'389';
    private $ldapconn;
    public static function get_instance($user, $pwd, $host=null, $port=null) {
        if (! self::$instance) {
            self::$instance = new Login_Ldap ( $user, $pwd, $host, $port );
        }
        return self::$instance;
    }
    private function __construct($user, $pwd, $host, $port) {
        $this->ldaphost = APF::get_instance()->get_config('ldap_host');
        $this->ldapport = APF::get_instance()->get_config('ldap_port');
        $this->user = $user;
        $this->pwd = $pwd;
        if ($host && $port) {
            $this->ldaphost = $host;
            $this->ldapport = $port;
        }
        register_shutdown_function ( array (
                $this,
                "shutdown"
        ) );
    }
    private function get_connect() {
        if (! $this->ldapconn) {
            $this->ldapconn = ldap_connect ( $this->ldaphost, $this->ldapport );
            if($this->ldapconn){
                ldap_set_option ( $this->ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
            }
            //else{
                //debug
                //exit('eror ldap exit');
            //}
        }
        return $this->ldapconn;
    }
    /**
     * 检查用户身份
     */
    public function get_bind() {
        if ($this->get_connect ()) {
            $ldapbind = @ldap_bind ( $this->ldapconn, "anjuke\\" . $this->user, $this->pwd );
            if ($ldapbind) {
                return true;
            }
        }
        //ldap_get_option ( $this->ldapconn, LDAP_OPT_ERROR_STRING, $error );
        return false;
    }
    /**
    * 获取用户信息
    * @return array（用户名,英文名,邮件,工号）
    */
    public function getinfo() {
        if ($this->get_bind ()) {
            $staffname = $this->user;
            $sr = ldap_search ( $this->ldapconn, 'dc=anjuke, dc=net', "(sAMAccountName={$staffname})" );
            if ($sr) {
                $info = ldap_get_entries ( $this->ldapconn, $sr );
                $ldap_user = array ();
                if ($info ['count']) {
                    for($i = 0; $i < $info ['count']; $i ++) {
                        $ldap_user = array ();
                        $ldap_user ["chinese_name"] = $info [$i] ['displayname'] [0];
                        $ldap_user ["english_name"] = $info [$i] ['samaccountname'] [0];
                        $ldap_user ["email"] = $info [$i] ['mail'] [0];
                        $ldap_user ["code"] = $info [$i] ['description'] [0];
                    }
                }
                unset($info);
                return $ldap_user;
            }
            return false;

        }
    }

    /**
    */
    public  function shutdown() {
        ldap_close ( $this->ldapconn );
    }
}